<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, reactive, ref, useTemplateRef, watch } from 'vue';
import { fetchCheckCaptcha, fetchGetCaptcha } from '@/service/api/auth';
import { resetSizeOptions } from '../utils/util';
import { aseEncrypt } from '../utils/ase';
import type { ImageStyle, Instance } from '../utils/util';

defineOptions({ name: 'VerifyPoints' });

interface Props {
  mode?: string;
  captchaType: string;
  vSpace?: number;
  imgSize?: ImageStyle;
  barSize?: ImageStyle;
  defaultImg?: string;
}

interface SetSize {
  imgHeight: number;
  imgWidth: number;
  barHeight: number;
  barWidth: number;
}

interface Point {
  x: number;
  y: number;
}

interface Emit {
  (event: 'setClickShow', bool: boolean): void;
  (event: 'ready'): void;
  (event: 'success', data: CommonType.RecordObject): void;
  (event: 'error'): void;
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'fixed',
  vSpace: 5,
  imgSize: () => ({
    width: '310px',
    height: '155px'
  }),
  barSize: () => ({
    width: '310px',
    height: '40px'
  }),
  defaultImg: ''
});

const emit = defineEmits<Emit>();

const verifyPoints = useTemplateRef<HTMLDivElement>('verifyPoints');
const canvas = useTemplateRef<HTMLDivElement>('canvas');
const instance = getCurrentInstance();

/** 后端返回的ase加密秘钥 */
const secretKey = ref('');
/** 默认需要点击的字数 */
const checkNum = ref(3);
/** 选中的坐标信息 */
const fontPos = ref([]);
/** 用户点击的坐标 */
const checkPosArr = ref<Point[]>([]);
/** 点击的记数 */
const num = ref(1);
/** 后端获取到的背景图片 */
const pointBackImgBase = ref('');
/** 后端返回的点击字体顺序 */
const poinTextList = ref<string[]>([]);
/** 后端返回的token值 */
const backToken = ref('');

const setSize = reactive<SetSize>({
  imgHeight: 0,
  imgWidth: 0,
  barHeight: 0,
  barWidth: 0
});

const tempPoints = ref<Point[]>([]);
const text = ref('');
const barAreaColor = ref();
const barAreaBorderColor = ref();
const showRefresh = ref(true);
const bindingClick = ref(true);

watch(
  () => props.captchaType,
  () => {
    init();
  },
  { immediate: true }
);

onMounted(() => {
  const el = instance?.proxy?.$el;
  el.onselectstart = () => false;
});

/** 加载页面 */
async function init() {
  fontPos.value.splice(0, fontPos.value.length);
  checkPosArr.value.splice(0, checkPosArr.value.length);
  num.value = 1;
  getPictrue();
  await nextTick();
  /** 重新设置宽度高度 */
  Object.assign(setSize, resetSizeOptions(instance?.proxy as Instance, props.imgSize, props.barSize));
  emit('ready');
}

function canvasClick(e: MouseEvent) {
  checkPosArr.value.push(getMousePos(e));
  if (num.value === checkNum.value) {
    num.value = createPoint(getMousePos(e));
    // 按比例转换坐标值
    checkPosArr.value = pointTransfrom(checkPosArr.value, setSize);
    // 等创建坐标执行完
    setTimeout(async () => {
      // 发送后端请求
      const captchaVerification = secretKey.value
        ? aseEncrypt(`${backToken.value}---${JSON.stringify(checkPosArr.value)}`, secretKey.value)
        : `${backToken.value}---${JSON.stringify(checkPosArr.value)}`;
      const params: LoginApi.CheckCaptchaParams = {
        captchaType: props.captchaType,
        pointJson: secretKey.value
          ? aseEncrypt(JSON.stringify(checkPosArr.value), secretKey.value)
          : JSON.stringify(checkPosArr.value),
        token: backToken.value
      };
      const { data } = await fetchCheckCaptcha(params);
      if (data) {
        barAreaColor.value = '#4cae4c';
        barAreaBorderColor.value = '#5cb85c';
        text.value = '验证成功';
        bindingClick.value = false;
        if (props.mode === 'pop') {
          setTimeout(() => {
            emit('setClickShow', false);
            refresh();
          }, 1500);
        }
        emit('success', { code: captchaVerification });
      } else {
        emit('error');
        barAreaColor.value = '#d9534f';
        barAreaBorderColor.value = '#d9534f';
        text.value = '验证失败';
        setTimeout(() => {
          refresh();
        }, 700);
      }
    }, 400);
  }
  if (num.value < checkNum.value) {
    num.value = createPoint(getMousePos(e));
  }
}

// 获取坐标
function getMousePos(e: MouseEvent) {
  const x = e.offsetX;
  const y = e.offsetY;
  return { x, y };
}

// 创建坐标点
function createPoint(pos: Point) {
  tempPoints.value.push({ ...pos });
  num.value += 1;
  return num.value;
}

function refresh() {
  tempPoints.value.splice(0, tempPoints.value.length);
  barAreaColor.value = '#000';
  barAreaBorderColor.value = '#ddd';
  bindingClick.value = true;
  fontPos.value.splice(0, fontPos.value.length);
  checkPosArr.value.splice(0, checkPosArr.value.length);
  num.value = 1;
  getPictrue();
  text.value = '验证失败';
  showRefresh.value = true;
}

/** 请求背景图片和验证图片 */
async function getPictrue() {
  const params: LoginApi.GetCaptchaParams = {
    captchaType: props.captchaType,
    clientUid: localStorage.getItem('point') || '',
    ts: Date.now()
  };
  try {
    const { data } = await fetchGetCaptcha(params);
    if (data) {
      pointBackImgBase.value = data.originalImageBase64;
      backToken.value = data.token;
      secretKey.value = data.secretKey;
      poinTextList.value = data.wordList || [];
      text.value = `请依次点击【${poinTextList.value.join(',')}】`;
    }
  } catch {
    // text.value = data.repMsg;
  } finally {
    // 判断接口请求次数是否失效
    // if (res.code === '6201') {
    //   pointBackImgBase.value = '';
    // }
  }
}

/** 坐标转换函数 */
function pointTransfrom(pointArr: Point[], imgSize: SetSize) {
  const newPointArr = pointArr.map(p => {
    const x = Math.round((310 * p.x) / imgSize.imgWidth);
    const y = Math.round((155 * p.y) / imgSize.imgHeight);
    return { x, y };
  });
  return newPointArr;
}
</script>

<template>
  <div ref="verifyPoints" class="relative">
    <div class="verify-img-out">
      <div
        class="verify-img-panel"
        :style="{
          width: setSize.imgWidth,
          height: setSize.imgHeight,
          'background-size': setSize.imgWidth + ' ' + setSize.imgHeight,
          'margin-bottom': vSpace + 'px'
        }"
      >
        <div v-show="showRefresh" class="verify-refresh z-3" @click="refresh">
          <i class="iconfont icon-refresh" />
        </div>
        <img
          ref="canvas"
          :src="pointBackImgBase ? 'data:image/png;base64,' + pointBackImgBase : defaultImg"
          class="block size-full"
          @click="bindingClick ? canvasClick($event) : undefined"
        />

        <div
          v-for="(tempPoint, index) in tempPoints"
          :key="index"
          class="point-area absolute z-9999 h-20px w-20px rounded-full bg-[#1abd6c] text-center color-white leading-20px"
          :style="{
            top: tempPoint.y - 10 + 'px',
            left: tempPoint.x - 10 + 'px'
          }"
        >
          {{ index + 1 }}
        </div>
      </div>
    </div>
    <!-- 'height': this.barSize.height, -->
    <div
      class="verify-bar-area"
      :style="{
        width: setSize.imgWidth,
        color: barAreaColor,
        'border-color': barAreaBorderColor,
        'line-height': barSize.height
      }"
    >
      <span class="verify-msg">{{ text }}</span>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
